package cn.lei.netty.herostory.cmdhandler;

import cn.lei.netty.herostory.BroadCaster;
import cn.lei.netty.herostory.model.User;
import cn.lei.netty.herostory.model.UserManager;
import cn.lei.netty.herostory.msg.GameMsgProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;

/**
 * 用户移动消息处理器
 *
 * @author lil
 */
public class UserMoveToCmdHandler implements ICmdHandler<GameMsgProtocol.UserMoveToCmd> {
    @Override
    public void handle(ChannelHandlerContext ctx, GameMsgProtocol.UserMoveToCmd cmd) {
        //用户移动消息

        //考虑安全问题,协议中不带userId,从哪里取呢?(谁发取谁-用户入场时添加到session中)
        Integer userId = (Integer) ctx.channel().attr(AttributeKey.valueOf("userId")).get();

        if (userId == null) {
            return;
        }

        // 获取已有用户
        User existUser = UserManager.getByUserId(userId);

        if (null == existUser) {
            return;
        }

        long nowTime = System.currentTimeMillis();

        existUser.moveState.fromPosX = cmd.getMoveFromPosX();
        existUser.moveState.fromPosY = cmd.getMoveFromPosY();
        existUser.moveState.toPosX = cmd.getMoveToPosX();
        existUser.moveState.toPosY = cmd.getMoveToPosY();
        existUser.moveState.startTime = nowTime;

        GameMsgProtocol.UserMoveToResult.Builder userMoveBuilder = GameMsgProtocol.UserMoveToResult.newBuilder();
        userMoveBuilder.setMoveUserId(userId);
        userMoveBuilder.setMoveFromPosX(cmd.getMoveFromPosX());
        userMoveBuilder.setMoveFromPosY(cmd.getMoveFromPosY());
        userMoveBuilder.setMoveToPosX(cmd.getMoveToPosX());
        userMoveBuilder.setMoveToPosY(cmd.getMoveToPosY());
        userMoveBuilder.setMoveStartTime(nowTime);

        //构建结果并广播
        GameMsgProtocol.UserMoveToResult newResult = userMoveBuilder.build();
        BroadCaster.broadcast(newResult);
    }
}
